//import Vue from 'vue'
import Vuex from 'vuex'




import moduleUser from '@/store/user.js'
import moduleDept from '@/store/dept.js'
import moduleMessage from '@/store/message.js'
import moduleWs from '@/store/ws.js'
import moduleMessagelist from '@/store/message_list.js'


//Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
	        socketTask: null
	},
	mutations: {
		WEBSOCKET_INIT (state, url) {
			state.socketTask = uni.connectSocket({
				url,  // url是websocket连接ip
				success () {
					console.log('websocket====连接成功')
				}
			})
			state.socketTask.onOpen((res) => {
				console.log('WebSocket连接正常打开中...！')
				// 注：只有连接正常打开中 ，才能正常收到消息
				state.socketTask.onMessage(res => {
					
					console.log('收到服务器内容===：' + res.data)
					// 发送到页面
					 uni.$emit('websocket-data', res.data);
				});
			})
		},
		WEBSOCKET_SEND (state, data) {
			state.socketTask.send({
			   data,
			   async success() {
				   console.log('消息发送成功===')
			   },
		   })
		},
		CLOSE_SOCKET (state) {
			if (!state.socketTask) return
			state.socketTask.close({
				success (res) {
					console.log('关闭成功===', res)
				},
				fail (err) {
					console.log('关闭失败===', err)
				}
			})
		}
	},
	actions: {
		WEBSOCKET_INIT({
			commit
					   }, url) {
			commit('WEBSOCKET_INIT', url)
		},
		WEBSOCKET_SEND({
			commit
					   }, data) {
			commit('WEBSOCKET_SEND', data)
		},
		CLOSE_SOCKET({
			commit
					 }) {
			commit('CLOSE_SOCKET')
		}
	},
	
  modules: {
    // 挂载购物车的 vuex 模块，模块内成员的访问路径被调整为 m_cart，例如：
    // 购物车模块中 cart 数组的访问路径是 m_cart/cart
    'm_dept': moduleDept,
    'm_user': moduleUser,
	'm_message': moduleMessage,
	'm_ws': moduleWs,
	'm_messagelist': moduleMessagelist
  }
})
export default store
